package com.github.catvod.spider;

import com.github.catvod.crawler.Spider;
import com.github.catvod.net.SSLSocketFactoryCompat;
import com.github.catvod.utils.Util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author 文又七
 * 笔盒
 */
public class BiHe extends Spider {

    private final String siteUrl = "https://biheq7.com/";


    /**
     * 首页内容
     */
    @Override
    public String homeContent(boolean filter) {
        try {

            JSONObject movieType = new JSONObject()
                    .put("type_id", "all")
                    .put("type_name", "最近更新");

            JSONObject teleplayType = new JSONObject()
                    .put("type_id", "自拍")
                    .put("type_name", "自拍");

            JSONObject varietyType = new JSONObject()
                    .put("type_id", "教师")
                    .put("type_name", "教师");

            JSONObject anime = new JSONObject()
                    .put("type_id", "寻花")
                    .put("type_name", "寻花");

            JSONObject zhubo = new JSONObject()
                    .put("type_id", "主播")
                    .put("type_name", "主播");

//            JSONObject sex = new JSONObject()
//                    .put("type_id", "5")
//                    .put("type_name", "午夜");

            JSONArray classes = new JSONArray()
                    .put(movieType)
                    .put(teleplayType)
                    .put(varietyType)
                    .put(anime)
                    .put(zhubo);

            // filter 二级筛选 end
            JSONObject result = new JSONObject()
                    .put("class", classes);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 分类页面
     *
     * @param tid    影片分类id值
     * @param pg     第几页
     * @param extend 筛选
     * @return 返回 json 字符串
     */
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) {
        try {

            String cateUrl = "";
            if (tid == "all") {
                cateUrl = String.format("https://dsqdfsr2rkem4.cloudfront.net/api_v3/vod/list?type_id=%s&pageSize=24&page=%s", tid, pg);
            } else {
                cateUrl = String.format("https://dsqdfsr2rkem4.cloudfront.net/api_v3/vod/tag?keyword=%s&page=%s&pageSize=24", tid, pg);
            }


            // 分类页链接拼接后应该是类似这样的：
            // cateUrl = "https://www.bilituys.com/bilishow/1-大陆-time-喜剧-国语----2---2020.html";
            String content = getWebContent(cateUrl);
            System.out.println(content);
            JSONArray episodes = new JSONObject(content).getJSONObject("data").getJSONArray("list");
            JSONArray videos = new JSONArray();
            for (int i = 0; i < episodes.length(); i++) {
                JSONObject jsonObject = (JSONObject) episodes.get(i);
                String vid = jsonObject.optString("vod_id");
                String name = jsonObject.optString("vod_name");
                String pic = jsonObject.optString("vod_pic");
                String remark = "";
                JSONObject vod = new JSONObject()
                        .put("vod_id", vid + "###" + name)
                        .put("vod_name", name)
                        .put("vod_pic", pic)
                        .put("vod_remarks", remark);
                videos.put(vod);
            }
//
            JSONObject result = new JSONObject()
                    .put("page", Integer.parseInt(pg))
                    .put("pagecount", Integer.MAX_VALUE)
                    .put("limit", 24)
                    .put("total", Integer.MAX_VALUE)
                    .put("list", videos);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getWebContent(String targetUrl) throws IOException {
        String ip = Util.getRandomIp();
        String ua = Util.getRandomUserAgent();
        Request request = new Request.Builder()
                .url(targetUrl)
                .get()
                .addHeader("User-Agent", ua)
                //.addHeader("Host", "55dy1.vip")
                .addHeader("x-forwarded-for", ip)
                .build();


        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
                //.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.9.149", 10811)))
                .sslSocketFactory(new SSLSocketFactoryCompat(), SSLSocketFactoryCompat.trustAllCert)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.body() == null) return "";
        String content = response.body().string();
        response.close();
        return content;
    }

    /**
     * 详情页
     */
    @Override
    public String detailContent(List<String> ids) {
        try {
//            JSONObject detailObj = new JSONObject(ids.get(0));
//            String detailUrl = detailObj.optString("detailUrl");
//            String pic = detailObj.optString("pic");

//            String durl = ids.get(0);

            String content = getWebContent(siteUrl + "play?id=" + ids.get(0).split("###")[0]);

            Document detailPage = Jsoup.parse(content);
            //Elements sourceList = detailPage.select("[class=stui-content__playlist sort-list maxheight clearfix]");
            //Elements sourceHeader = detailPage.select("h3[class=title]");

            String vodPlayUrl = siteUrl + "play?id=" + ids.get(0).split("###")[0];
            // 影片标题
            String title = ids.get(0).split("###")[1];
            // 图片
            String pic = "";

            String typeName = "";
            String year = "";
            String area = "";
            String remark = "";
            //演员
            String actor = "mddd";
            //导演
            String director = "md";
            //简介
            String brief = "md123";

            String vodPlayFrom = "BiHe";


            // 影片名称、图片等赋值
            JSONObject vod = new JSONObject()
                    .put("vod_id", ids.get(0).split("###")[0])
                    .put("vod_name", title)
                    .put("vod_pic", pic)
                    .put("type_name", typeName) // 影片类型
                    .put("vod_year", year) // 影片年份
                    .put("vod_area", area) // 影片地区
                    .put("vod_remarks", remark)
                    .put("vod_actor", actor)
                    .put("vod_director", director)
                    .put("vod_content", brief)
                    .put("vod_play_from", vodPlayFrom)
                    .put("vod_play_url", vodPlayUrl.toString());

            JSONArray jsonArray = new JSONArray()
                    .put(vod);
            JSONObject result = new JSONObject()
                    .put("list", jsonArray);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 搜索
     *
     * @param key 关键字/词
     */
    @Override
    public String searchContent(String key, boolean quick) {
        try {
            String searchUrl = String.format("https://d2tt22hwjkw203.cloudfront.net/api_v3/vod/search?keyword=%s&page=1&pageSize=24", key);

            String searchResult = getWebContent(searchUrl);
            JSONArray episodes = new JSONObject(searchResult).getJSONObject("data").getJSONArray("list");
            JSONArray videos = new JSONArray();

            for (int i = 0; i < episodes.length(); i++) {
                JSONObject jsonObject = (JSONObject) episodes.get(i);
                String vid = jsonObject.optString("vod_id");
                String name = jsonObject.optString("vod_name");
                String pic = jsonObject.optString("vod_pic");
                String remark = "";
                JSONObject vod = new JSONObject()
                        .put("vod_id", vid + "###" + name)
                        .put("vod_name", name)
                        .put("vod_pic", pic)
                        .put("vod_remarks", remark);
                videos.put(vod);
            }
            JSONObject result = new JSONObject()
                    .put("list", videos);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String playerContent(String flag, String playUrl, List<String> vipFlags) {
        try {

//            String content = getWebContent(playUrl);
//            String url = Jsoup.parse(content).getElementsByTag("iframe").attr("src");
//
////            content = content.substring(content.indexOf("\"link_pre\""));
//            content = content.substring(content.indexOf("\"url\":"));
//            content = content.substring(content.indexOf("\"url\":") + 7, content.indexOf("\",")).replace("\\", "");

            // HashMap<String, String> header = new HashMap<>();
            //   header.put("user-agent", userAgent);
            JSONObject result = new JSONObject()
                    .put("parse", 1)
                    .put("header", getHeaders(""))
                    .put("playUrl", "")
                    .put("url", playUrl);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    private HashMap<String, String> getHeaders(String url) {
        String ip = Util.getRandomIp();
        String ua = Util.getRandomUserAgent();
        HashMap<String, String> headers = new HashMap<>();
        //headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
        headers.put("User-Agent", ua);
        //headers.put("Host", "55dy1.vip");
        headers.put("x-forwarded-for", ip);
        return headers;
    }
}
